package com.liuxingzhiwu.ruijishangcheng.controller;


import com.liuxingzhiwu.ruijishangcheng.common.R;
import com.liuxingzhiwu.ruijishangcheng.utils.FileNameUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    private String path = "D:\\software engineering\\java\\project\\ruijishangcheng\\target\\classes\\dishImage";;

    /**
     * 上传文件
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(HttpServletRequest request,MultipartFile file){  //这里参数名和前端参数名一致
        //提取生成文件名UUID + 上传图片后缀.jpg  .png
        //获取文件的原始名称
        String FileName = file.getOriginalFilename();
        String saveFileName = FileNameUtil.getUUIDFileName()+FileNameUtil.getFileType(FileName);

        //得到项目中图片存储的路径
        //String path = request.getServletContext().getRealPath("/dishImage"); //获取的是文件夹image_big的路径，一定要/
        //path = "D:\\software engineering\\java\\project\\ruijishangcheng\\target\\classes\\dishImage"; //获取的是文件夹image_big的路径，一定要/

        //转存
        try {
            file.transferTo(new File(path+ File.separator+saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(saveFileName);
    }

    /**
     * 下载文件
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        //设置响应对象的编码
        response.setContentType("image/jpeg");

        try {
            //输入流，通过输入流读取文件
            FileInputStream fileInputStream = new FileInputStream(new File(path+ File.separator+name));

            //输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



}
